package com.itheima.controller;

import com.itheima.pojo.User;
import com.itheima.resp.Code;
import com.itheima.resp.Msg;
import com.itheima.resp.Result;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 控制层
 * @author chenshan
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 查询所有
     * @return Result
     */
    @GetMapping
    public Result selectAll() {
        List<User> list = userService.list();

        Integer code;
        String message;
        if (list != null && list.size() > 0) {
            code = Code.GET_OK;
            message = Msg.GET_OK;
        } else {
            code = Code.GET_ERR;
            message = Msg.GET_ERR;
        }

        return new Result(code, list, message);
    }

    /**
     * 根据id查询用户信息
     * @param id 用户id
     * @return Result
     */
    @GetMapping("/{id}")
    public Result selectAll(@PathVariable Integer id) {
        User user = userService.getById(id);

        Integer code;
        String message;
        if (user != null) {
            code = Code.GET_OK;
            message = Msg.GET_OK;
        } else {
            code = Code.GET_ERR;
            message = Msg.GET_ERR;
        }

        return new Result(code, user, message);
    }

    @PostMapping
    public Result add(@RequestBody User user) {
        boolean flag = userService.save(user);

        Integer code;
        String message;
        if (flag) {
            code = Code.SAVE_OK;
            message = Msg.SAVE_OK;
        } else {
            code = Code.SAVE_ERR;
            message = Msg.SAVE_ERR;
        }

        return new Result(code, flag, message);
    }

    /**
     * 根据id进行修改
     * @param user 用户信息（根据id）
     * @return v
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        boolean flag = userService.updateById(user);

        Integer code;
        String message;
        if (flag) {
            code = Code.UPDATE_OK;
            message = Msg.UPDATE_OK;
        } else {
            code = Code.UPDATE_ERR;
            message = Msg.UPDATE_ERR;
        }

        return new Result(code, flag, message);
    }

    /**
     * 根据id删除
     * @param id 用户id
     * @return Result
     */
    @DeleteMapping("/{id}")
    public Result update(@PathVariable Integer id) {
        boolean flag = userService.removeById(id);

        Integer code;
        String message;
        if (flag) {
            code = Code.DELETE_OK;
            message = Msg.DELETE_OK;
        } else {
            code = Code.DELETE_ERR;
            message = Msg.DELETE_ERR;
        }

        return new Result(code, flag, message);
    }
}
